define(["require",
'config/appregister',
'business/EnterpriseReg/service/reghttp',
"jquery",
'business/services/cutPicture',
"upfull",
"business/EnterpriseReg/directive/upload6",
], function(require, app, httpServices) {
	
	app.controller('enterpriseregCtrl', function($scope, $http, $state) {
		$scope.usersrc = "";
		function getimgfy(imgSrc){
			return  imgSrc.substr(imgSrc.indexOf("base64,")+7,imgSrc.length)
		};
		//企业注册验证码图片请求
		loGin();
		//点击验证码图片动作
		$scope.gg = function() {
			loGin();
		};
		//聚焦方法
		$scope.allname = function() {
			$(".allname").css("opacity", 0);
		};
		$scope.abbr = function() {
			$(".abbr").css("opacity", 0);
		};
		
		//企业成立时间
		Setuptime();
		function Setuptime() {
			var nowtime = new Date();
			var year = nowtime.getFullYear();
			$scope.months = [];
			$scope.years = [];
			for(var i=1800;i<year;i++) {
				var arr = {
					year:i
				}
				$scope.years.push(arr);
			}
			for(var i=1;i<13;i++) {
				var arr = {
					month:i
				}
				$scope.months.push(arr);
			}
		};
		
		$scope.gotoindex = function() {
			$state.go("indexCtrl");
		}
		
		//点击省
		$scope.schange = function(x) {
			$("#ss,#cs,#as").hide();
			getCity(x.provinceId);
		};
		//点击市
		$scope.cchange = function(x) {
			$("#ss,#cs,#as").hide();
			getArea(x.regionId);
		};		
		//点击县区
		$scope.achange = function(x) {
			$("#ss,#cs,#as").hide();
		};			
		//获取省
		getprovince();
		function getprovince(){
			$("#ss").hide();
			var req = {
				type:'GET',
				uri:'getProvinceList'
			};
			httpServices.selectfn(req).success(function(data){
				if(!data)return;
				$scope.$apply(function(){
					if(data.code==0) {
						$scope.province = data.data;
					}else {
						console.log(data.msg);
					}
				});
			}).error(function(){
				console.log("省请求失败");
			});	
		};
		//获取城市
		function getCity(a) {
			$("#cs").hide();
			var req = {
				type:'GET',
				uri:'getRegionListInProvince',
				data:{
					provinceId: a
				}
			};
			httpServices.selectfn(req).success(function(data){
				if(!data)return;
				$scope.$apply(function(){
					if(data.code==0) {
						$scope.region = data.data;
						getArea($scope.region[0].regionId);
						$("#ss").hide();
						$scope.regionname = $scope.region[0];
					}else {
						console.log(data.msg);
					}
				});
			}).error(function(){
				console.log("市请求失败");
			});				
		};
		
		//获取区
		function getArea(a) {
			$("#as").hide();
			var req = {
				type:'GET',
				uri:'getAreaListInRegionId',
				data:{
					regionId: a
				}
			};
			httpServices.selectfn(req).success(function(data){
				if(!data)return;
				$scope.$apply(function(){
					if(data.code==0) {
						$scope.areas = data.data;
						$("#cs").hide();
						$scope.areaname = $scope.areas[0];
					}else {
						console.log(data.msg);
					}
				});
			}).error(function(){
				console.log("区/县请求失败");
			});				
		};
		
		
	
		//企业性质
		nature();
		function nature() {
			var req = {
				type:'GET',
				uri:'getCompanyNatrueList',
			};
			httpServices.selectfn(req).success(function(data){
				if(!data)return;
				$scope.$apply(function(){
					if(data.code==0) {
						$scope.nature = data.data;								
					}else {
						console.log(data.msg);
					}					
				});
			}).error(function(data){
				alert("企业性质请求失败");
			});
		};
		
		//企业规模
		scale();
		function scale() {
			var req = {
				type:'GET',
				uri:'getScaleList',
			};
			httpServices.selectfn(req).success(function(data){
				if(!data)return;
				$scope.$apply(function() {
					if(data.code==0) {
						$scope.scale = data.data;								
					}else {
						console.log(data.msg);
					}					
				});
			}).error(function(data){
				alert("企业规模请求失败");
			});
		};
		
		//企业分类
		Gui();
		function Gui() {
			var req = {
				type:'GET',
				uri:'getGuildList',
			};
			httpServices.selectfn(req).success(function(data){
				if(!data)return;
				$scope.$apply(function() {
					if(data.code==0) {
						$scope.gui = data.data;								
					}else {
						console.log(data.msg);
					}					
				});
			}).error(function(data){
				alert("企业分类请求失败");
			});
		};

		//下面是企业注册第二大步
		$scope.lastreg = function() {
			lastReg();
		};
		$scope.$on('previewPath',function(a,b,c){
			$scope.credential = b;
		})
		
		//企业注册
		function lastReg() {
			var guild = $("#guis option:selected").val(), //企业分类
				scale = $("#scales option:selected").val(), //企业规模
				nature = $("#natures option:selected").val(), //企业性质
				fullname = $(".fullname").val(),
				shortname = $(".shortname").val(),
				province = $("#shen option:selected").val(),
				region = $("#shi option:selected").val(),
				areaid = $("#qu option:selected").val(),
				address = $(".address").val(),
				foundtime = $scope.setUpTime1.year+"-"+$scope.setUpTime2.month+"-"+'1',
//				credential = $("#previewImg").attr("src"),
				introduction = $(".introduction").val();
			if(guild&&scale&&nature&&fullname&&shortname&&province&&region&&areaid&&address&&foundtime&&$scope.credential&&introduction) {
				var req = {
					type:'post',
					uri:'regCompanyWithFillInfo',
					data:{
						guildId:guild,
						scaleId:scale,
						natureId:nature,
						logo: getimgfy($scope.usersrc),
						fullName:fullname,
						shortName:shortname,
						provinceId:$scope.provincename.provinceId,
						regionId:$scope.regionname.regionId,
						areaId:$scope.areaname.areaId,
						address:address,
						foundTime:foundtime,
						credential:$scope.credential,
						introduction:introduction,
						credential:$scope.credential,
						verifyToken:$scope.verifyToken
					}
				};
				$scope.s = 3;
				$.ajax({
					type: "post",
					dataType: "json",
					data:req.data,
					url: "http://"+allUrl+":8080/elink_user/api/company/regCompanyWithFillInfo",
					success: function(result) {
						if(result.code==0) {
							$scope.$apply(function(){
								$(".regbox2").hide();
								$(".regbox3").show();
								var time = setInterval(function(){
									if($scope.s<=0) {
										$scope.s = 0;
										clearInterval(time);
										$state.go("enterpriselogin");
									}else {
										$scope.s--;
									}
								},1000)								
							})			
						}else {
							console.log(JSON.stringify(result));
							alert(result.msg);
						}	
					},
					error: function(jqXHR) {
						console.log("error")
					}
				});			
			}else {
				alert("请填写完整信息");
			}

		};

		//input检验
		var in1 = 0;
		var in2 = 0;
		var in3 = 0;
		var in4 = 0;
		var in5 = 0;

		//点击下一步
		$scope.doit = function() {
			var che = $(".input6").is(":checked");
			if(in1 == 1 && in2 == 1 && in3 == 1 && in5 == 1 && che == true) {
				getNext();
			} else {
				console.log("请检查邮箱/密码/手机/验证码是否正确输入");
			};
		};
		var mytime;
		//获取短信验证码方法
		$scope.getMsg = function() {
			console.log($scope.verifyToken,"这是获取短信验证码的");
			
			if(in3 == 1 && in4 == 1) {
				var phone = $(".input3").val();
				var code = $(".input4").val().toUpperCase();
				var req = {
					type:'POST',
					uri:'regCompanyWithSendPhoneCode',
					data:{
						phone:phone,
						verifyCode:code,
						verifyToken:$scope.verifyToken
					}
				};
				httpServices.companylogin(req).success(function(data){
					if(!data)return;
					$scope.$apply(function(){
						if(data.code == 0) {
							$('.msg').unbind("click");
							$(".msg").html("重新获取(<span id=" + 'time' + ">150</span>)");
							var timer = $("#time").html();
							mytime = setInterval(function() {
								if(timer > 0) {
									timer--;
									timer = timer;
								} else {
									clearInterval(mytime);
									$(".msg").html("重新获取");
									$('.msg').bind("click");
									loGin();
								}
								$("#time").html(timer);
							}, 1000)
						} else {
							alert(data.msg);
							loGin();
						};						
					});
				}).error(function(data){
					alert("获取短信验证码请求失败");
					loGin();
				});				
			}else {
				alert("请检查验证码或手机号是否正确输入");
//				loGin();				
			};
			
		};

		//下一步
		function getNext() {
			console.log($scope.verifyToken,"这是下一步的");
			
			var email = $(".input1").val();
			var phone = $(".input3").val();
			var pswd = $(".input2").val();
			var vfcode = $(".input5").val().toUpperCase();

			var req = {
				type:'POST',
				uri:'regCompanyWithCheckPhoneCode',
				data:{
					email: email,
					phone: phone,
					passwd: pswd,
					verifyCode: vfcode,
					verifyToken: $scope.verifyToken
				}
			};			
			httpServices.companylogin(req).success(function(data){
					console.log("下一步成功");
					clearInterval(mytime);
					$(".regbox").hide();
					$(".regbox2").show();				
			}).error(function(data){
					console.log("下一步请求失败");
					loGin();				
			});
		};

		//请求验证码图片方法
		function loGin() {
			var req = {
				type: 'GET',
				uri: 'regCompanyWithVerifyCode',
			};
			httpServices.getcodeHttpService(req).success(function(data){	
				$scope.$apply(function(){
					if(data.code==0){
						$scope.regimgsrc = data.data.img;
						var arr = data.data.verifyToken;
						var arred = arr.split(",");
						$scope.verifyToken = arred[0];
						var expireTime = arred[1];
						var exp = new Date();
						exp.setTime(exp.getTime()+expireTime);
						document.cookie = "verifyToken="+$scope.verifyToken+";expires="+exp.toGMTString();
						console.log($scope.verifyToken,"这是第一步的");
					}else {
						console.log(data.msg);
					}					
				})
			}).error(function(data){
				alert("验证码请求失败")
			});
		};

		//失焦提示
		$scope.tip1 = function() {
			var regex_email = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			var val1 = $(".input1").val();
			if(val1 == '') {
				$(".tip1").css("opacity", 1);
				$(".tip1").html("请输入企业邮箱").css("color","red");
			} else if(regex_email.test(val1)) {
				var req = {
					type:'GET',
					uri:'checkEmail',
					data:{
						email: val1				
					}
				};
				httpServices.checkfn(req).success(function(data){
					$scope.$apply(function(){
						if(data.code == 0){
							$(".tip1").css("opacity", 1).html("该邮箱可以使用").css("color","green");
							in1 = 1;
						}else {
							in1 = 0;
							$(".tip1").css("opacity", 1).html("该邮箱已存在").css("color","red");
						}						
					});
				}).error(function(data){
						in1 = 0;
						console.log("检验邮箱请求失败");				
				});			
			}else{
				in1 = 0;
				$(".tip1").css("opacity", 1).html("格式错误！");
			};
		};

		$scope.tip2 = function() {
			var regex_pswd = /^[\w]{6,16}$/;
			var val2 = $(".input2").val();
			if(val2 == "") {
				$(".tip2").css("opacity", 1);
				$(".tip2").html("请设置6-18个字符的密码");
			} else if(regex_pswd.test(val2)) {
				console.log("格式正确")
				in2 = 1;
				$(".tip2").css("opacity", 0);

			} else {
				$(".tip2").css("opacity", 1);
				$(".tip2").html("格式错误");
			};
		};

		$scope.tip3 = function() {
			var regex_phone = /^1[3|4|5|7|8]\d{9}$/;
			var val3 = $(".input3").val();
			if(val3 == "") {
				$(".tip3").css("opacity", 1);
				$(".tip3").html("请输入手机号码");
			} else if(regex_phone.test(val3)) {
				var req = {
					type:'GET',
					uri:'checkPhone',
					data:{
						phone: val3				
					}
				};
				httpServices.checkfn(req).success(function(data){
					$scope.$apply(function(){
						if(data.code == 0){
							$(".tip3").css("opacity", 1).html("该手机号可以使用").css("color","green");
							in3 = 1;
						}else {
							in3 = 0;
							$(".tip3").css("opacity", 1).html("该手机号已存在").css("color","red");
						}						
					});
				}).error(function(data){
						in3 = 0;
						console.log("检验邮箱请求失败");				
				});			
			} else {
				$(".tip3").html("格式错误");
			};
		};

		$scope.tip4 = function() {
			var val4 = $(".input4").val();
			if(val4 == '') {
				$(".tip4").css("opacity", 1);
				$(".tip4").html("请输入验证码");
			} else {
				in4 = 1;
			};
		};
		
		$scope.tip5 = function() {
			var val5 = $(".input5").val();
			if(val5 == '') {
				$(".tip5").css("opacity", 1);
				$(".tip5").html("请输入短信验证码");
			} else {
				in5 = 1;
			};
		};

//		//上传图片及时预览
//		function preview1(file) {
//			$("#gai").html("修改logo");
//			var img = new Image(),
//				url = img.src = URL.createObjectURL(file)
//			var $img = $(img)
//			img.onload = function() {
//				URL.revokeObjectURL(url)
//				$('#preview').empty().append($img)
//			};
//		};
//
//		function preview2(file) {
//			var reader = new FileReader()
//			reader.onload = function(e) {
//				var $img = $('<img>').attr("src", e.target.result)
//				$('.divpic').empty().append($img)
//			};
//			reader.readAsDataURL(file)
//		};
//
//		$(function() {
//			$('[type=file]').change(function(e) {
//				if(this.id === "subpic") {
//					var file = e.target.files[0]
//					preview1(file)
//				} else {
//					var file = e.target.files[0]
//					preview2(file)
//				};
//			});
//		});

		//点击注册
		$scope.doyes = function() {
			$(".regbox2").hide();
			$(".regbox3").show();
		};

		$scope.toone = function() {
			$state.go("login",{type:"register"});
		};

		$scope.tona = function() {
			$state.go("enterpriselogin");
		};
		
		
//		
//	accessid = ''
//accesskey = ''
//host = ''
//policyBase64 = ''
//signature = ''
//callbackbody = ''
//filename = ''
//key = ''
//expire = 0
//g_object_name = ''
//g_object_name_type = ''
//now = timestamp = Date.parse(new Date()) / 1000;
//
//function send_request() {
//	var xmlhttp = null;
//	if(window.XMLHttpRequest) {
//		xmlhttp = new XMLHttpRequest();
//	} else if(window.ActiveXObject) {
//		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
//	}
//	if(xmlhttp != null) {
//		serverUrl = 'http://"+allUrl+":8089/elink_aliyun/api/oss/getMediaOSSAuth?seed=a4c29669f28682b0f9a3c0aa0e11b7dd&authToken=7b0231fcd89569169b2352b31937971c'
//		xmlhttp.open("GET", serverUrl, false);
//		xmlhttp.send(null);
//		return xmlhttp.responseText
//	} else {
//		alert("Your browser does not support XMLHTTP.");
//	}
//};
//
//function check_object_radio() {
//	g_object_name_type = 'random_name';
//}
//
//function get_signature() {
//	//可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
//	now = timestamp = Date.parse(new Date()) / 1000;
//	if(expire < now + 3) {
//		body = send_request()
//		var obj = eval("(" + body + ")");
//		host = obj['host']
//		policyBase64 = obj['policy']
//		accessid = obj['accessid']
//		signature = obj['signature']
//		expire = parseInt(obj['expire'])
//		callbackbody = obj['callback']
//		key = obj['dir']
//		console.log('key='+key);
//		return true;
//	}
//	return false;
//};
//
//function random_string(len) {　　
//	len = len || 32;　　
//	var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';　　
//	var maxPos = chars.length;　　
//	var pwd = '';　　
//	for(i = 0; i < len; i++) {　　
//		pwd += chars.charAt(Math.floor(Math.random() * maxPos));
//	}
//	return pwd;
//}
//
//function get_suffix(filename) {
//	pos = filename.lastIndexOf('.')
//	suffix = ''
//	if(pos != -1) {
//		suffix = filename.substring(pos)
//	}
//	return suffix;
//}
//
//function calculate_object_name(filename) {
//	if(g_object_name_type == 'local_name') {
//		g_object_name += "${filename}"
//	} else if(g_object_name_type == 'random_name') {
//		suffix = get_suffix(filename)
//		g_object_name = key + random_string(10) + suffix
//	}
//	return ''
//}
//
//function get_uploaded_object_name(filename) {
//	console.log(filename);
//	if(g_object_name_type == 'local_name') {
//		tmp_name = g_object_name
//		tmp_name = tmp_name.replace("${filename}", filename);
//		return tmp_name
//	} else if(g_object_name_type == 'random_name') {
//		return g_object_name
//	}
//}
//
//function set_upload_param(up, filename, ret) {
//	if(ret == false) {
//		ret = get_signature()
//	}
//	g_object_name = key;
//	if(filename != '') {
//		suffix = get_suffix(filename)
//		calculate_object_name(filename)
//	}
//	new_multipart_params = {
//		'key': g_object_name,
//		'policy': policyBase64,
//		'OSSAccessKeyId': accessid,
//		'success_action_status': '200', //让服务端返回200,不然，默认会返回204
//		'callback': callbackbody,
//		'signature': signature,
//	};
//
//	up.setOption({
//		'url': host,
//		'multipart_params': new_multipart_params
//	});
//
//	up.start();
//}
//
//var uploader = new plupload.Uploader({
//	runtimes: 'html5,flash,silverlight,html4',
//	browse_button: 'selectfiles',
//	//multi_selection: false,
//	container: document.getElementById('container'),
//	flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
//	silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
//	url: 'http://oss.aliyuncs.com',
//
//	filters: {
//		mime_types: [ //只允许上传图片和zip,rar,video文件
//			{
//				title: "Image files",
//				extensions: "jpg,gif,png,bmp"
//			}, {
//				title: "Zip files",
//				extensions: "zip,rar"
//			}, {
//				title: "Video files",
//				extensions: "rmvb"
//			}
//		],
//		max_file_size: '1000mb', //最大只能上传10mb的文件
//		prevent_duplicates: true //不允许选取重复文件
//	},
//
//	init: {
//		PostInit: function() {
////			document.getElementById('ossfile').innerHTML = '';
//			/*document.getElementById('postfiles').onclick = function() {
//				set_upload_param(uploader, '', false);
//				return false;
//			};*/
//		},
//
//		FilesAdded: function(up, files) {
//			
//			//set_upload_param(uploader, '1111s', false);
////			plupload.each(files, function(file) {
////				document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>' +
////					'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>' +
////					'</div>';
////			});	
//			set_upload_param(uploader, '', false);
//			return false;
//		},
//
//		BeforeUpload: function(up, file) {
//			check_object_radio();
//			set_upload_param(up, file.name, true);
//		},
//
//		/*UploadProgress: function(up, file) {
//			var d = document.getElementById(file.id);
//			d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
//			var prog = d.getElementsByTagName('div')[0];
//			var progBar = prog.getElementsByTagName('div')[0]
//			console.log(up.total.bytesPerSec);
//			progBar.style.width = 2 * file.percent + 'px';
//			progBar.setAttribute('aria-valuenow', file.percent);
//		},*/
//
//		FileUploaded: function(up, file, info) {
//			
//			if(info.status == 200) {
//				var previewImgUrl = host+'/'+get_uploaded_object_name(file.name);
//				document.getElementById('previewImg').src = previewImgUrl;
//			}
//			/*if(info.status == 200) {
//				document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'upload to oss success, object name:' + get_uploaded_object_name(file.name);
//			} else {
//				document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
//			}*/
//		},
//
//		Error: function(up, err) {
//			/*if(err.code == -600) {
//				document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小"));
//			} else if(err.code == -601) {
//				document.getElementById('console').appendChild(document.createTextNode("\n选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型"));
//			} else if(err.code == -602) {
//				document.getElementById('console').appendChild(document.createTextNode("\n这个文件已经上传过一遍了"));
//			} else {
//				document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
//			}*/
//		}
//	}
//});
//
//uploader.init();
//		
//		
//		
		
		

	})
})